package com.lay.http.core;

import com.google.gson.Gson;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class PostRequest extends RequestBody {
    private Boolean jsonFormat = false;
    protected PostRequest(String url) {
        super(url);
    }

    @Override
    public ResponseBody send() {
        PostResponse responseBody = new PostResponse();
        BufferedWriter writer = null;
        InputStream inputStream = null;
        HttpURLConnection connection = null;
        try {
            URL httpUrl = new URL(url);
            connection = (HttpURLConnection)httpUrl.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setConnectTimeout(getConnectTimeout());
            connection.setReadTimeout(getReadTimeout());
            connection.setRequestMethod("POST");
            boolean jsonFormat = false;
            for(Map.Entry<String, String> entry : getHeaders().entrySet()){
                connection.setRequestProperty(entry.getKey(), entry.getValue());
                if("Content-Type".equalsIgnoreCase(entry.getKey()) && entry.getValue().contains("application/json")){
                    jsonFormat = true;
                }
            }
            connection.connect();
            if(getParams() != null) {
                writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
                StringBuilder sb = new StringBuilder();
                if(jsonFormat){
                    String json = new Gson().toJson(getParams());
                    sb.append(json);
                } else {
                    Set<Map.Entry<String, Object>> entries = getParams().entrySet();
                    for(Map.Entry entry : entries){
                        sb.append(entry.getKey() + "=" + entry.getValue()).append("&");
                    }
                    if(sb.length() > 0){
                        sb.deleteCharAt(sb.length() - 1);
                    }
                }
                writer.write(sb.toString());
                writer.flush();
            }
            responseBody.setReaponseCode(connection.getResponseCode());
            responseBody.setHeader(connection.getHeaderFields());
            inputStream = connection.getInputStream();
            responseBody.handle(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(connection != null){
                connection.disconnect();
            }
        }
        return responseBody;
    }
}
